package model

import (
	"gitee.com/xiaozefeng/billing-server/pkg/auth"
	"github.com/jinzhu/gorm"
	"github.com/lexkong/log"
	"github.com/satori/go.uuid"
	"time"
)

type User struct {
	BaseModel
	Name     string `json:"name" form:"name"`
	Password string `json:"password" form:"password"`
}

func (user User) TableName() string {
	return "tb_user"
}

func (user *User) Create() error {
	return DB.Self.Create(&user).Error
}

func (user *User) BeforeCreate(scope *gorm.Scope) error {
	u4, _ := uuid.NewV4()
	scope.SetColumn("Id", u4.String())
	scope.SetColumn("created_time", time.Now())
	scope.SetColumn("created_by", "system")
	scope.SetColumn("updated_time", time.Now())
	scope.SetColumn("updated_by", "system")
	return nil
}

func (user *User) BeforeUpdate() error {
	user.UpdatedTime = time.Now()
	return nil
}

func DeleteUser(id string) error {
	user := User{}
	user.Id = id
	return DB.Self.Delete(&user).Error
}

func (user *User) Update() error {
	return DB.Self.Save(&user).Error
}

func ListUser(offset, limit int) ([]*User, uint64, error) {
	if limit == 0 {
		limit = 10
	}
	users := make([]*User, 0)

	var count uint64
	if err := DB.Self.Model(&User{}).Count(&count).Error; err != nil {
		return users, count, err
	}
	if err := DB.Self.Offset(offset).Limit(limit).Order("created_time asc").Find(&users).Error; err != nil {
		return users, count, err
	}

	return users, count, nil
}

func GetUserById(id string) (*User, error) {
	user := User{}
	user.Id = id
	d := DB.Self.First(&user)
	return &user, d.Error
}

func GetUserByName(name string) (*User, error) {
	user := User{}
	user.Name = name
	d := DB.Self.First(&user)
	return &user, d.Error
}

func (user *User) Encrypt() (err error) {
	log.Infof("encrypt() password: [%s]", user.Password)
	user.Password, err = auth.Encrypt(user.Password)
	return err
}
